<script setup lang="ts">
import { defineComponent, ref } from 'vue'
import { Message, FormInstance } from '@arco-design/web-vue'
import { useUserStore } from '@/store'
import { encrypt } from '@/utils/auth'
import { getPublicKeyUsingGet } from '@/api/authController'
import { updateUserUsingPut } from '@/api/userController'
import { useRouter } from 'vue-router'
defineOptions({
  name: 'Account'
})
const userStore = useUserStore()
const router = useRouter()

// 用户更新请求对象
const userUpdateRequest = ref<API.UserUpdateRequest>({
  id: userStore.user.id,
  password: '',
  rePassword: '',
  email: '',
  phone: ''
})

// 密码表单
const passwordFormRef = ref<FormInstance>()
const passwordRules = {
  password: [
    { required: true, message: '请输入新密码' },
    { minLength: 8, message: '密码长度不能小于8位' },
    { maxLength: 32, message: '密码长度不能超过32位' },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,32}$/,
      message: '密码必须包含大小写字母和数字'
    }
  ],
  rePassword: [
    { required: true, message: '请确认新密码' },
    {
      validator: (value: string, callback: (error?: string) => void) => {
        if (value !== userUpdateRequest.value.password) {
          callback('两次输入的密码不一致')
        }
        callback()
      }
    }
  ]
}

// 控制输入框显示状态
const showEmailInput = ref(false)
const showPhoneInput = ref(false)

// 处理修改密码
const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return
  const errors = await passwordFormRef.value.validate()
  if (errors) return

  try {
    userUpdateRequest.value.id = userStore.user.id
    const publicKey: any = await getPublicKeyUsingGet()
    const encryptedPassword = encrypt(userUpdateRequest.value.password as string, publicKey)
    const encryptedRePassword = encrypt(userUpdateRequest.value.rePassword as string, publicKey)
    // TODO: 调用修改密码接口
    const res: any = await updateUserUsingPut({
      ...userUpdateRequest.value,
      password: encryptedPassword,
      rePassword: encryptedRePassword
    })
    if (res.code == 0) {
      Message.success('密码修改成功,请重新登录')
      userStore.logout()
      router.push('/login')
    } else {
      Message.error(res?.message || '密码修改失败')
    }
    userUpdateRequest.value.password = ''
    userUpdateRequest.value.rePassword = ''
  } catch (error) {
    Message.error('密码修改失败：' + error)
  }
}

// 处理修改邮箱
const handleUpdateEmail = async () => {
  try {
    // TODO: 调用修改邮箱接口
    userUpdateRequest.value.id = userStore.user.id
    const res: any = await updateUserUsingPut(userUpdateRequest.value)
    if (res.code == 0) {
      Message.success('邮箱修改成功')
      userUpdateRequest.value.email = ''
      showEmailInput.value = false
      await userStore.getUserInfo()
    } else {
      Message.error(res?.message || '邮箱修改失败')
    }
  } catch (error) {
    Message.error('邮箱修改失败：' + error)
  }
}

// 处理修改手机
const handleUpdatePhone = async () => {
  try {
    // TODO: 调用修改手机接口
    userUpdateRequest.value.id = userStore.user.id
    const res: any = await updateUserUsingPut(userUpdateRequest.value)
    if (res.code == 0) {
      Message.success('手机号修改成功')
      userUpdateRequest.value.phone = ''
      showPhoneInput.value = false
      await userStore.getUserInfo()
    } else {
      Message.error(res?.message || '手机号修改失败')
    }
  } catch (error) {
    Message.error('手机号修改失败：' + error)
  }
}

// 处理取消修改邮箱
const handleCancelEmail = () => {
  showEmailInput.value = false
  userUpdateRequest.value.email = ''
}

// 处理取消修改手机
const handleCancelPhone = () => {
  showPhoneInput.value = false
  userUpdateRequest.value.phone = ''
}
</script>

<template>
  <div class="account-container">
    <div class="section-item">
      <div class="item-header">基本信息</div>
      <div class="item-content">
        <div class="info-row">
          <div class="info-label">用户名</div>
          <div class="info-value">
            <span class="value-text">{{ userStore.user.username }}</span>
            <span class="info-tip">用户名不可修改</span>
          </div>
        </div>
      </div>
    </div>

    <div class="section-item">
      <div class="item-header">安全设置</div>
      <div class="item-content">
        <div class="info-row">
          <div class="info-label">修改密码</div>
          <div class="info-value">
            <div class="input-area">
              <a-form
                :model="userUpdateRequest"
                layout="horizontal"
                ref="passwordFormRef"
                :style="{ width: '100%' }"
              >
                <a-form-item field="password" :rules="passwordRules.password" label="新密码">
                  <a-input-password
                    v-model="userUpdateRequest.password"
                    placeholder="请输入新密码"
                    allow-clear
                    validate-trigger="blur"
                  />
                </a-form-item>
                <a-form-item field="rePassword" :rules="passwordRules.rePassword" label="重复密码">
                  <a-input-password
                    v-model="userUpdateRequest.rePassword"
                    placeholder="请确认新密码"
                    allow-clear
                    validate-trigger="blur"
                  />
                </a-form-item>
                <div class="form-actions">
                  <a-button type="primary" size="small" @click="handleUpdatePassword">
                    修改密码
                  </a-button>
                </div>
              </a-form>
            </div>
            <span class="info-tip">密码不小于8位</span>
          </div>
        </div>

        <div class="info-row">
          <div class="info-label">邮箱绑定</div>
          <div class="info-value">
            <div class="input-area">
              <template v-if="userStore.user.email && !showEmailInput">
                <span class="value-text">{{ userStore.user.email }}</span>
                <a-button type="text" size="small" @click="showEmailInput = true"> 修改 </a-button>
              </template>
              <template v-else>
                <div class="bind-input-group" v-if="showEmailInput">
                  <a-input
                    v-model="userUpdateRequest.email"
                    placeholder="请输入邮箱"
                    allow-clear
                    :style="{ width: '240px' }"
                  />
                  <div class="action-buttons">
                    <a-button type="primary" size="small" @click="handleUpdateEmail">
                      确定
                    </a-button>
                    <a-button size="small" @click="handleCancelEmail"> 取消 </a-button>
                  </div>
                </div>
                <template v-else>
                  <span class="empty-text">未绑定邮箱</span>
                  <a-button type="primary" size="small" @click="showEmailInput = true">
                    立即绑定
                  </a-button>
                </template>
              </template>
            </div>
            <span class="info-tip">邮箱用于通知您最新的消息</span>
          </div>
        </div>

        <div class="info-row">
          <div class="info-label">手机绑定</div>
          <div class="info-value">
            <div class="input-area">
              <template v-if="userStore.user.phone && !showPhoneInput">
                <span class="value-text">{{ userStore.user.phone }}</span>
                <a-button type="text" size="small" @click="showPhoneInput = true"> 修改 </a-button>
              </template>
              <template v-else>
                <div class="bind-input-group" v-if="showPhoneInput">
                  <a-input
                    v-model="userUpdateRequest.phone"
                    placeholder="请输入手机号"
                    allow-clear
                    :style="{ width: '240px' }"
                  />
                  <div class="action-buttons">
                    <a-button type="primary" size="small" @click="handleUpdatePhone">
                      确定
                    </a-button>
                    <a-button size="small" @click="handleCancelPhone"> 取消 </a-button>
                  </div>
                </div>
                <template v-else>
                  <span class="empty-text">未绑定手机号</span>
                  <a-button type="primary" size="small" @click="showPhoneInput = true">
                    立即绑定
                  </a-button>
                </template>
              </template>
            </div>
            <span class="info-tip">手机号用于其他协作人员联系您</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.section-item {
  background-color: #fff;
  border-radius: 4px;
  margin-bottom: 16px;
}

.item-header {
  padding: 12px 20px;
  font-size: 15px;
  font-weight: 500;
  color: var(--color-text-1);
  border-bottom: 1px solid var(--color-border);
}

.item-content {
  padding: 0 20px;
}

.info-row {
  display: flex;
  padding: 16px 0;
  border-bottom: 1px solid var(--color-border);
}

.info-row:last-child {
  border-bottom: none;
}

.info-label {
  width: 80px;
  font-size: 14px;
  color: var(--color-text-2);
  line-height: 32px;
}

.info-value {
  flex: 1;
  min-width: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
}

.input-area {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
}

.value-text {
  font-size: 14px;
  color: var(--color-text-1);
}

.empty-text {
  font-size: 14px;
  color: var(--color-text-3);
}

.info-tip {
  font-size: 13px;
  color: var(--color-text-3);
  width: 120px;
  text-align: right;
  flex-shrink: 0;
}

:deep(.arco-form-item) {
  margin-bottom: 12px;
}

:deep(.arco-form-item-layout-horizontal) {
  display: flex;
  align-items: center;
}

:deep(.arco-form-item-label-col) {
  width: 80px;
  text-align: right;
  padding-right: 12px;
}

:deep(.arco-form-item-wrapper) {
  flex: 1;
  min-width: 0;
  width: 240px;
}

.form-actions {
  padding-left: 80px;
  display: flex;
  justify-content: center;
  width: 320px;
  margin-top: 16px;
  margin-left: 0;
}

.bind-input-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  height: 32px;
  align-items: center;
}
</style>
